﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Windows;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting;

namespace Kokomo.PeInspector.Profiler
{
	class ProfilerMonitor : MarshalByRefObject, IProfilerMonitor
	{
		//[DllImport("oleaut32.dll")]
		//private static extern int RegisterActiveObject(
		//    IntPtr pUnk,
		//    ref Guid rclsid,
		//    int dwFlags,
		//    out IntPtr pdwRegister
		//    );

		public ProfilerMonitor()
		{
			this.InstanceName = "KokomoProfiler_" + Guid.NewGuid();
			this.PortName = @"\\.\pipe\" + this.InstanceName;
			this.InstanceUri = "ipc://" + this.InstanceName;
		}

		public string PortName { get; private set; }
		public string InstanceName { get; private set; }
		public string InstanceUri { get; private set; }

		public void Register()
		{
			IpcChannel channel = new IpcChannel(this.InstanceName);
			ChannelServices.RegisterChannel(channel, false);
			RemotingServices.Marshal(this, this.InstanceUri);
		}
		//public void Register()
		//{
		//    IntPtr thisUnknown = Marshal.GetIUnknownForObject(this);
		//    Guid instanceID = this.InstanceID;
		//    IntPtr rotCookie;
		//    int res = RegisterActiveObject(
		//        thisUnknown,
		//        ref instanceID,
		//        0,
		//        out rotCookie
		//        );

		//    this.RotCookie = rotCookie;
		//}

		//public IntPtr RotCookie { get; private set; }

		public void Connect()
		{
			MessageBox.Show("Profiler monitor received connection");
		}
	}
}
